package wu.seal.utils

import wu.seal.utils.inner.TempDirHelper
import java.io.File
import java.util.zip.ZipInputStream

class FileDeal {

    /**
     * 找到文件名包含某个字符串或某个字符串正则的的文件集合
     */
    fun getMatchesNameFiles(files: List<File>, matchName:String): List<File> {
        return files.filter {
            val b = matchName.toRegex().containsMatchIn(it.name)
            platformPrint("${it.name} 匹配文件名规则 $matchName?  : $b")
            b
        }
    }


    /**
     * 获取一个文件夹下所有的文件
     */
    fun getAllFilesInDir(dirPath: String): List<File> {
        val files = lazy{ mutableListOf<File>()}
        val dir = File(dirPath)
        if (dir.exists().not()) {
            return listOf()
        } else {
            dir.listFiles().forEach {
                if (it.isDirectory) {
                    files.value.addAll(getAllFilesInDir(it.absolutePath))
                } else {
                    files.value.add(it)
                }
            }
        }
        return files.value
    }

    fun containsZip(dir: File):Boolean {
        var containsZip = false

        dir.listFiles().forEach {
            if (it.name.endsWith(".zip")) {
                containsZip =  true
            } else if (it.isDirectory) {
                if (containsZip(it)) {
                    containsZip = true
                }
            }
        }
        return containsZip

    }

    /**
     * 解压当前目录及子目录下的所有zip文件
     */
    fun unzipAllFilesRecursiveAndDeleteZipedFiles(dir: File) {
        dir.listFiles().forEach {
            if (it.isDirectory) {
                unzipAllFilesRecursiveAndDeleteZipedFiles(it)
            } else {
                if (it.name.endsWith(".zip")) {
                    platformPrint("开始解压文件${it.name}")
                    if (nowInMacRuntime()) {
                        unZipFileForMac(it)
                    } else {
                        it?.run {
                            unzipFile(it)
                        }
                    }
                    //删除自己，防止后面再次解压已经解压出来的文件为zip时所有目录时重复解压父zip文件
                    it.delete()
                }
            }
        }
    }

    private fun unzipFile(zipFile: File) {
        ZipInputStream(zipFile.inputStream()).use { zipIS->
            do {
                val entry = zipIS.nextEntry
                entry?.let { zipEntry ->
                    if (zipEntry.isDirectory) {
                        //不处理为文件夹的情况,后面递规的时候会把这种情况给处理掉
                    } else {
                        val fileName = zipEntry.name
                        val newFile = File(zipFile.parent,fileName)
                        newFile.outputStream().use {
                            it.writer().write(zipIS.reader(charset("utf-8")).readText())
                        }
                    }
                }
            }while (entry!=null)
        }
        platformPrint("解压文件${zipFile.name} OK")
    }

    private fun unZipFileForMac(it: File) {
        val execUnzip = Runtime.getRuntime().exec(arrayOf("unzip", "-o", it.absolutePath, "-d", it.parentFile.absolutePath))
        platformPrint("解压文件${it.name} OK")
        platformPrint(execUnzip.inputStream.reader().readText())
        platformPrint(execUnzip.errorStream.reader().readText())
    }


    /**
     * 解压当前目录及子目录下的所有rar文件
     */
    fun unRarAllFilesRecursive(dir: File) {

        val execUnRar = Runtime.getRuntime().exec(arrayOf("unrar", "x", "*.rar"))!!
        print(execUnRar.inputStream.reader().readText())
        print(execUnRar.errorStream.reader().readText())

        dir.listFiles().forEach {
            if (it.isDirectory) {
                unRarAllFilesRecursive(it)
            }
        }
    }

    /**
     * 删除当前目录及子目录下的所有zip文件
     */
    fun removeAllZipFilesRecursive(dir: File) {
        dir.listFiles().forEach {
            if (it.isDirectory) {
                removeAllZipFilesRecursive(it)
            } else {
                if (it.name.endsWith(".zip")) {
                   it.delete()
                }
            }
        }
    }

    fun removeAllMacCacheFiles(dir: File) {
        dir.listFiles().forEach {
            if (it.isDirectory&&it.name=="__MACOSX") {
                it.deleteRecursively()

            } else if (it.isDirectory) {
                removeAllMacCacheFiles(it)
            }
        }
    }
    /**
     * 删除当前目录及子目录下的所有rar文件
     */
    fun removeAllRarFilesRecursive(dir: File) {
        dir.listFiles().forEach {
            if (it.isDirectory) {
                removeAllZipFilesRecursive(it)
            } else {
                if (it.name.endsWith(".rar")) {
                    it.delete()
                }
            }
        }
    }

    /**
     * 获取工作目录的临时目录
     */
    fun getWorkDirTempDir(workDir: File): File =
        TempDirHelper().createDir(workDir.absolutePath)
}